<?php
namespace app\admin\controller;


use app\common\service\RbacSrv;
use think\Request;
use app\common\controller\BaseController;
use View;
use Db;
use Session;
use Gregwar\Captcha\CaptchaBuilder;
use app\admin\validate\Login;
use think\Exception;


class Common extends BaseController
{


    public function imgcode(){
        $builder = new CaptchaBuilder();
        $builder->build($width = 180, $height = 60, './resource/font/simple.ttf');
        $phrase = $builder->getPhrase();
        Session::set('LoginVerify', md5($phrase));


        $builder->output();

        $header = [
            'Content-type'=>'image/jpeg',
        ];

        return response('', 200, $header);
    }

    public function login(){



        return $this->fetch();
    }

    public function loginDo(Request $request){

        $param = $request->param();

        $validate= new Login();
        try{
            $result = $validate->checkDo($param);
        }catch (Exception $e){
            return $this->error($e->getMessage());
        }

        if (!$result) {
            return $this->error($validate->getError());
        }


        $userInfo = Db::table('qi_user')->where('username',$param['username'])->find();

        if(empty($userInfo)){
            return $this->error('帐号不存在或密码错误!');
        }

        if($userInfo['password'] != md5($param['password'])){
            return $this->error('帐号不存在或密码错误!');
        }

        $loginInfo = [
            'uid'=>$userInfo['id'],
            'username'=>$userInfo['username'],
            'remark'=>$userInfo['remark'],
        ];

        Session::set('loginInfo', $loginInfo);


        $rabc = new RbacSrv();
        $rabc->getUserAccess($userInfo['id']);

        return $this->redirect('/admin/Manage/home');

    }

    public function logout(){

        Session::flush();
        return $this->success('退出成功！', url('/admin/common/login'));
    }

}
